package com.wolfeyes.framework.web.filter;

import com.wolfeyes.common.utils.network.web.RequestIdUtils;
import com.wolfeyes.framework.web.context.WebContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @title 请求ID的过滤器
 * @className RequestIdFilter
 * @author yanyljava
 * @create 2022-01-14 21:25
 */
public class RequestIdFilter implements Filter {
	
	/**
	 * @title 过滤器的初始化操作
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
	}

	/**
	 * @title 过滤逻辑的核心操作方法
	 */
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		//if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
			MDC.put("REQUEST_ID", this.getRequestId());
			try {
				filterChain.doFilter(request, response);
			} finally {
				RequestIdUtils.removeRequestId();
				MDC.clear();
			}

		//}
	}

	/**
	 * @title 过滤器的销毁操作
	 */
	@Override
	public void destroy() {
		
	}

	private String getRequestId() {
		
		// 优先从header获取，gateway会设置
		HttpServletRequest request = WebContextUtils.getRequest();
		String requestId = request.getHeader("x-request-id");
		if(StringUtils.isEmpty(requestId)){
			RequestIdUtils.generateRequestId();
			return RequestIdUtils.getRequestId().toString();
		}
		// 设值回RequestIdUtils当中
		UUID uuid = UUID.fromString(requestId);
		RequestIdUtils.generateRequestId(uuid);
		return requestId;
	}
	
}

